<template>
  <el-dialog
    class="public-dialog"
    :title="`新增物流商运输方式管理`"
    width="560"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div>
      <VForm
        ref="form"
        :fieldList="fieldList"
        :model="model"
        :rules="rules"
        :options="formOption"
        :disabled="disabled"
        :originOption="optionsData"
      >
      </VForm>
    </div>

    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? '关闭' : '取消' }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from 'element-plus'
import VForm from '@/components/Form/index.vue'
import { overallOptions } from '@/api/public'

import {
  createLogisticsShipping,
  logisticsShippingDetail,
  updateLogisticsShipping,
} from '../../../api'

const props = defineProps({
  id: { type: [String, Number], default: '' },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue', 'refresh', 'close'])

const formOption = {
  inline: true,
  labelPosition: 'top',
}

const form = ref()

const model = ref({ logistics_api_id: '' })
const loading = ref()
const optionsData = ref({})

const publicStyle = { style: { width: '196px' } }

const handleChangeAPi = async e => {
  const formValues = await form.value.getFormValues()
  model.value = {
    ...formValues,
    api_ident: e.api_ident,
  }
}

const fieldList = [
  {
    field: 'logistics_api_id',
    type: 'select',
    ...publicStyle,
    originField: 'mapLogisticsApi',
    label: '物流商API名称',
    options: {
      labelKey: 'api_name',
    },
    valueKey: 'logistics_api_id',
    itemProps: {
      onChange: handleChangeAPi,
    },
  },
  {
    field: 'api_ident',
    ...publicStyle,
    label: '物流商API标识',
    disabled: true,
  },
  {
    field: 'cn_name',
    full: true,
    itemStyle: { width: '100%' },
    label: '物流商渠道运输方式中文名',
  },
  {
    field: 'en_name',
    full: true,
    itemStyle: { width: '100%' },
    label: '物流商渠道运输方式英文名',
  },
  { field: 'use_code', ...publicStyle, label: '运输方式代码' },
  { field: 'shipping_type', ...publicStyle, label: '运输方式类型' },
]

const rules = {
  logistics_api_id: [
    { required: true, message: '请选择物流商API', trigger: 'blur' },
  ],
  cn_name: [
    {
      required: true,
      message: '请输入物流商渠道运输方式中文名',
      trigger: 'change',
    },
  ],
  en_name: [
    {
      required: true,
      message: '物流商渠道运输方式英文名',
      trigger: 'change',
    },
  ],
}

onMounted(() => {
  getOption()
})

watch(
  () => props.id,
  val => {
    if (val) {
      nextTick(() => {
        getDetail(val)
      })
    }
  }
)

const getOption = async () => {
  const { data } = await overallOptions({ params: 'map.logistics-api' })
  let _options = data['mapLogisticsApi']
  if (_options) {
    optionsData.value = data
  }
}

const getDetail = async id => {
  try {
    loading.value = true
    const { data } = await logisticsShippingDetail({ id })
    const { logistics_api_id } = data
    const logisticsApiData = optionsData.value['mapLogisticsApi']
    const _logistics_api_id = logisticsApiData.find(
      n => n.logistics_api_id === logistics_api_id
    )
    // console.warn(logisticsApiData, _logistics_api_id, logistics_api_id)
    model.value = {
      ...data,
      logistics_api_id: _logistics_api_id,
      api_ident: _logistics_api_id?.api_ident,
    }
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleSave = async () => {
  try {
    loading.value = true

    const { logistics_api_id = {}, ...formValues } = await form.value.submit()

    const isEdit = !!model.value?.id
    const api = {
      add: createLogisticsShipping,
      edit: updateLogisticsShipping,
    }
    const { code, message } = await api[isEdit ? 'edit' : 'add']({
      ...formValues,
      id: model.value?.id,
      logistics_api_id: logistics_api_id?.logistics_api_id,
    })
    if (code !== 200) {
      ElMessage.warning(message)
      return
    }
    handleClose(true)
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning('请检查表单信息')
    }

    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = async refresh => {
  model.value = {}
  await nextTick()
  form.value.resetForm?.()
  emit('update:modelValue', false)
  emit('close')
  if (refresh) emit('refresh')
}
</script>
